from django.core.exceptions import ValidationError
from django.db import transaction

from app.models import User,Employee
from datetime import datetime
from django.utils import timezone

from app.models import User, Employee, OrderItem, Order,MerchantInfo
from django.contrib.auth.hashers import check_password, make_password
from middleware.auth_middleware import generate_jwt_token
from middleware.util import make_response


class UserService:
    @staticmethod
    def login(username=None, password=None):
        if not username or not password:
            raise ValueError("用户名和密码不能为空")

        try:
            user = User.objects.get(username=username)
        except User.DoesNotExist:
            raise ValueError("用户名或密码错误")

        if not check_password(password, user.password_hash):
            raise ValueError("用户名或密码错误")

        token = generate_jwt_token(user.id, user.role)

        # 基础登录数据
        login_data = {
            "token": f"Bearer {token}",
            "role": user.role,
            "user_id": str(user.id),
            "username": user.username,
            "phone": user.phone,
        }

        # 检查是否为员工，如果是则添加员工信息
        try:
            employee = Employee.objects.get(
                user=user, 
                employment_status='active'
            )
            
            # 获取今日活动统计
            today = timezone.now().date()
            from app.models import EmployeeActivity
            today_activities = EmployeeActivity.objects.filter(
                employee=employee,
                activity_time__date=today
            )
            
            cook_count = today_activities.filter(activity_type='cook_dish').count()
            serve_count = today_activities.filter(activity_type='serve_dish').count()
            total_activities = cook_count + serve_count
            total_bonus = float(total_activities * employee.activity_bonus_per_count)

            # 添加员工信息到登录数据
            login_data.update({
                "is_employee": True,
                "employee_info": {
                    "real_name": employee.real_name,
                    "merchant_id": str(employee.merchant.merchant_id),
                    "merchant_name": employee.merchant.shop_name,
                    "hire_date": employee.hire_date.isoformat(),
                    "employment_status": employee.get_employment_status_display(),
                    "work_schedule": {
                        "work_start_time": employee.work_start_time.strftime("%H:%M:%S"),
                        "work_end_time": employee.work_end_time.strftime("%H:%M:%S"),
                        "monday": employee.monday_work,
                        "tuesday": employee.tuesday_work,
                        "wednesday": employee.wednesday_work,
                        "thursday": employee.thursday_work,
                        "friday": employee.friday_work,
                        "saturday": employee.saturday_work,
                        "sunday": employee.sunday_work,
                    },
                    "salary_info": {
                        "base_daily_salary": float(employee.base_daily_salary),
                        "activity_bonus_per_count": float(employee.activity_bonus_per_count),
                        "late_penalty_per_minute": float(employee.late_penalty_per_minute),
                        "early_leave_penalty_per_minute": float(employee.early_leave_penalty_per_minute)
                    },
                    "today_activities": {
                        "cook_count": cook_count,
                        "serve_count": serve_count,
                        "total_activities": total_activities,
                        "total_bonus": total_bonus
                    }
                }
            })
            
        except Employee.DoesNotExist:
            # 不是员工，只标记为普通用户
            login_data["is_employee"] = False

        # 如果是商家，添加商家信息
        if user.role == 'merchant':
            try:
                merchant_info = MerchantInfo.objects.get(merchant_id=user.id)
                login_data.update({
                    "merchant_info": {
                        "shop_name": merchant_info.shop_name,
                        "location": merchant_info.location,
                        "business_hours": merchant_info.business_hours,
                        "contact_info": merchant_info.contact_info,
                        "introduction": merchant_info.introduction,
                        "register_time": merchant_info.register_time.isoformat()
                    }
                })
            except MerchantInfo.DoesNotExist:
                logger.warning(f"商家用户 {user.id} 缺少商家信息")

        return make_response(
            code=200,
            message="登录成功",
            data=login_data
        )

    @staticmethod
    def register_with_phone(username, phone, password):
        """
        手机号 + 密码注册普通用户
        :param username: 昵称
        :param phone: 手机号
        :param password: 明文密码
        :return: 注册结果
        """
        if not phone or len(phone) != 11 or not phone.isdigit():
            raise ValidationError("手机号格式错误")

        if User.objects.filter(phone=phone).exists():
            raise ValidationError("该手机号已被注册")

        with transaction.atomic():
            hashed_password = make_password(password)
            user = User.objects.create(
                username=username,
                phone=phone,
                password_hash=hashed_password,
                role='customer'  # 默认为普通用户
            )

        return make_response(
            code=201,
            message="注册成功",
            data={
                "user_id": str(user.id),
                "role": user.role
            }
        )

    @staticmethod
    def register_with_wechat_openid(wechat_openid, phone=None, username=None):
        """
        微信 OpenID 注册（自动创建普通用户）
        :param wechat_openid: 微信用户标识
        :param phone: 绑定手机号（可选）
        :param username: 昵称（可选）
        :return: 用户信息或创建新用户
        """
        if User.objects.filter(wechat_openid=wechat_openid).exists():
            return make_response(
            code=409,
            message="该微信已绑定其他账号",
        )

        if phone and User.objects.filter(phone=phone).exists():
            raise ValidationError("该手机号已被占用")

        # 自动创建用户
        user = User.objects.create(
            username=username or f"user_{wechat_openid[:8]}",
            phone=phone,
            password_hash=None,
            role='customer',
            wechat_openid=wechat_openid
        )

        return {
            "code": 201,
            "message": "微信注册成功",
            "data": {
                "user_id": str(user.id),
                "role": user.role
            }
        }

    @staticmethod
    def get_user_info(user_id):
        """
        获取指定用户的基本信息（不含敏感数据）
        :param user_id: 用户的 UUID
        :return: JsonResponse 统一格式的响应
        """
        try:
            user = User.objects.get(id=user_id)
        except User.DoesNotExist:
            return make_response(code=404, message="用户不存在")

        return make_response(
            code=200,
            message="成功",
            data={
                "user_id": str(user.id),
                "username": user.username,
                "phone": user.phone,
                "role": user.role,
                "created_at": user.created_at.isoformat() if user.created_at else None
            }
        )